import { _decorator, Collider2D, Component, Contact2DType, EPhysics2DDrawFlags, instantiate, IPhysics2DContact, Label, Node, PhysicsSystem2D, Prefab, TERRAIN_HEIGHT_FACTORY } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('TestCollide2d')
export class TestCollide2d extends Component {

    @property(Prefab)
    moveItemPrefab: Prefab = null

    @property(Label)
    itemsNumberLabel: Label = null

    protected onLoad(): void {
        // PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.CenterOfMass;

        // |
        // EPhysics2DDrawFlags.Pair |
        // EPhysics2DDrawFlags.CenterOfMass |
        // EPhysics2DDrawFlags.Joint |
        // EPhysics2DDrawFlags.Shape;
    }

    start() {
        this.node.on(Node.EventType.CHILD_ADDED, this.changeLabel, this)
        this.node.on(Node.EventType.CHILD_REMOVED, this.changeLabel, this)

        // 注册全局碰撞回调函数
        if (PhysicsSystem2D.instance) {
            PhysicsSystem2D.instance.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            PhysicsSystem2D.instance.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }

        this.creatorItem()
    }

    private changeLabel() {
        this.itemsNumberLabel.string = "item数量:" + this.node.children.length.toString();
    }

    onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        console.log('onBeginContact', selfCollider, otherCollider,contact);
    }
    onEndContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体结束接触时被调用一次
        console.log('onEndContact');
        console.log('onBeginContact', selfCollider, otherCollider,contact);
    }

    private creatorItem(num_n_: number = 50) {
        for (let index = 0; index < num_n_; index++) {
            this.scheduleOnce(() => {
                this.node.addChild(instantiate(this.moveItemPrefab))
            }, 0.01)
        }
    }

    public editorEventAddItem() {
        this.creatorItem()
    }

    public editorEventRemoveItem() {
        for (let index = 0; index < 50; index++) {
            this.scheduleOnce(() => {
                const nd = this.node.children[index]
                if (nd) {
                    nd.destroy()
                }
            }, 0.1)
        }
    }
}
